<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    :width="width"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <div class="dialog-content-wrapper">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        :disabled="isView"
      >
        <!-- 基础表单项 -->
        <div class="box-padding">
          <template v-for="(rowItem, rowIndex) in formItems" :key="rowIndex">
            <div class="title" v-if="rowItem.title">{{ rowItem.title }}</div>
            <el-row :gutter="0">
              <el-col
                v-for="(item, colIndex) in rowItem.list"
                :key="colIndex"
                :span="item.span || 24"
              >
                <el-form-item
                  :label="item.label"
                  :prop="item.prop"
                  :rules="isView ? undefined : item.rules"
                >
                  <!-- 输入框 -->
                  <el-input
                    v-if="item.type === 'input'"
                    v-model="formData[item.prop]"
                    :placeholder="item.placeholder || `请输入${item.label}`"
                    :disabled="isView || item.disabled"
                    clearable
                  />
                  <!-- 身份证输入框 -->
                  <template v-if="item.type === 'inputSearch'">
                    <div>
                      <el-input
                        v-model="formData[item.prop]"
                        :placeholder="item.placeholder || `请输入${item.label}`"
                        :disabled="isView || item.disabled"
                        clearable
                      />
                      <el-select v-if="inputOptions.length > 0" v-model="selectedOption" placeholder="请选择">
                        <el-option
                          v-for="option in inputOptions"
                          :key="option.value"
                          :label="option.label"
                          :value="option.value"
                        />
                      </el-select>
                    </div>
                  </template>
                  <!-- 级联选择器 -->
                  <el-cascader
                    v-else-if="item.type === 'cascader'"
                    v-model="formData[item.prop]"
                    :options="item.options"
                    :props="item.props || defaultCascaderProps"
                    :placeholder="item.placeholder || `请选择${item.label}`"
                    :disabled="isView || item.disabled"
                    :show-all-levels="item.showAllLevels"
                    :clearable="true"
                    @change="(value) => item.onChange?.(value, formData)"
                  />
                  <template v-else-if="item.type === 'checkbox'">
                    <el-checkbox-group
                      v-model="formData[item.prop]"
                      :disabled="isView || item.disabled"
                    >
                      <el-checkbox
                        v-for="opt in item.options"
                        :key="opt.value"
                        :label="opt.value"
                      >
                        {{ opt.label }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </template>

                  <el-switch
                    v-else-if="item.type === 'switch'"
                    v-model="formData[item.prop]"
                    :active-value="1"
                    :inactive-value="2"
                    :active-text="item.activeText"
                    :inactive-text="item.inactiveText"
                    :disabled="isView || item.disabled"
                    inline-prompt
                  />

                  <!-- 树形选择 -->
                  <el-tree-select
                    v-else-if="item.type === 'tree'"
                    v-model="formData[item.prop]"
                    :data="item.options"
                    :props="item.props || defaultProps"
                    :placeholder="item.placeholder || `请选择${item.label}`"
                    :disabled="isView || item.disabled"
                    :multiple="item.multiple"
                    :show-checkbox="item.showCheckbox"
                    :check-strictly="item.checkStrictly"
                    :default-expand-all="item.defaultExpandAll"
                    clearable
                  />
                  <el-tree-select
                    default-expand-all
                    v-if="item.type === 'areaTree'"
                    v-model="formData[item.prop]"
                    filterable
                    :data="item.data"
                    :render-after-expand="false"
                  />
                  <!-- 选择器 -->
                  <el-select
                    v-else-if="item.type === 'select'"
                    v-model="formData[item.prop]"
                    @change="dialogSelect(!item.isSelected, $event)"
                    :placeholder="item.placeholder || `请选择${item.label}`"
                    :disabled="isView || item.disabled"
                    clearable
                  >
                    <el-option
                      v-for="opt in item.options"
                      :key="opt.value"
                      :label="opt.label"
                      :value="opt.value"
                    />
                  </el-select>

                  <!-- 日期选择器 -->
                  <el-date-picker
                    v-else-if="item.type === 'date'"
                    v-model="formData[item.prop]"
                    :type="item.dateType || 'date'"
                    :placeholder="item.placeholder || `请选择${item.label}`"
                    :disabled="isView || item.disabled"
                    :format="item.format || 'YYYY-MM-DD'"
                    :value-format="item.valueFormat || 'YYYY-MM-DD'"
                    clearable
                  />
                  <el-date-picker
                    v-else-if="item.type === 'datetime'"
                    v-model="formData[item.prop]"
                    :type="item.dateType || 'datetime'"
                    :placeholder="item.placeholder || `请选择${item.label}`"
                    :disabled="isView || item.disabled"
                    :format="item.format || 'YYYY-MM-DD HH:mm:ss'"
                    :value-format="item.valueFormat || 'YYYY-MM-DD HH:mm:ss'"
                    clearable
                  />
                  <!-- 单选框组 -->
                  <el-radio-group
                    v-else-if="item.type === 'radio'"
                    v-model="formData[item.prop]"
                    :disabled="isView || item.disabled"
                  >
                    <el-radio
                      v-for="opt in item.options"
                      :key="opt.value"
                      :label="opt.value"
                    >{{ opt.label }}</el-radio
                    >
                  </el-radio-group>

                  <!-- 文本域 -->
                  <el-input
                    v-else-if="item.type === 'textarea'"
                    v-model="formData[item.prop]"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 20 }"
                    :rows="item.rows || 3"
                    :placeholder="item.placeholder || `请输入${item.label}`"
                    :disabled="isView || item.disabled"
                    clearable
                  />
                  <RichText
                    v-else-if="item.type === 'richText'"
                    :content="formData[item.prop]"
                    @update="(value)=>htmlUpdate(value,item.prop)"
                    :disabled="isView || item.disabled"
                    />
                    <!-- 图片上传 -->
                    <UploadImageTable
                        v-model="formData[item.prop]"
                        v-else-if="item.type === 'uploadImage'"
                        :limit="item.limit || 1"
                        :is-new-record="isView"
                        :image-type="item.imageType || 'image/jpeg,image/png,image/gif,image/bmp,image/webp'"
                        :image-url="imageUrl || formData[item.prop] "
                        @handle-image-success="(newImageUrl) => handleImageSuccess(newImageUrl, item.prop)"
                    />
                  <!-- 文件上传 -->
                  <div v-else-if="item.type === 'uploadFile'">
                    <UploadFileTable
                      :file-type="item.fileType?item.fileType:''"
                      v-model="formData[item.prop]"
                      :limit="item.limit || 1"
                      :is-to-html="props.isToHtml"
                      :file-name="fileName ||formData[item.prop]"
                      @handleHtmlContent="handleHtmlContent"
                      @handle-file-success="(file) => handleFileSuccess(file, item.prop)"
                    />
                    <div v-if="isFileName && formData[item.prop]" style="display: flex; align-items: center; margin-top: 90px;">
                      <div style="margin-right: 10px;">{{ formData[item.prop] }}</div>
                      <el-button v-if="!props.isView" size="small" text type="primary" @click="FileDownload(formData[item.prop])">
                        下载文件
                      </el-button>
                      <el-button v-if="!props.isView" size="small" text type="warning" @click="FileDelete(formData[item.prop],item.prop)">
                        删除文件
                      </el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </div>
      </el-form>
    </div>
    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <template v-if="isView">
          <el-button type="primary" @click="handleClose">关 闭</el-button>
        </template>
        <template v-else>
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </template>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import UploadImageTable from "../../commons/uploadInmae.vue";
import UploadFileTable from "../../commons/uploadFile.vue";
import {getFile, removeFile} from "@/api/fileApi.js";
import RichText from "@/pages/account/components/richText.vue";
// Props定义
const props = defineProps({
  centralizedIsolationId: {
    type: Number,
    default: 0,
  },
  modelValue: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: "审核流程配置",
  },
  width: {
    type: String,
    default: "50%",
  },
  operationName: {
    type: String,
    default: "",
  },
  isView: {
    type: Boolean,
    default: false,
  },

  progressExtra: {
    type: String,
    default: "",
  },
  steps: {
    type: Array,
    default: () => [],
  },
  currentStep: {
    type: Number,
    default: 0,
  },
  // 表单相关
  formItems: {
    type: Array,
    default: () => [],
  },
  // 初始数据
  initialData: {
    type: Object,
    default: () => ({}),
  },
  isToHtml: {
    type: Boolean,
    default: false,
  }
});

const defaultProps = {
  children: "children",
  label: "label",
  value: "value",
};
const isFileName = ref(true);
// Emits
const emit = defineEmits([
  "update:modelValue",
  "submit",
  "cancel",
  "close",
  "refresh",
  "handleDialogSubmit",
  "handleHtmlContent",
  "dialogSelect"
]);

// 响应式数据
const dialogVisible = ref(false);
const formRef = ref(null);
const currentAuditLevel = ref(1);
const initFormData = (level) => {
  return {
    auditLevel: level, // 审核级别
    administrativeLevel: "", // 行政级别
    orgUnit: "", // 组织单位
    handleName: "", // 处理人员
    proResultReq: "", // 处理结果要求
    handleAgeing: 24, // 处理时效
  };
};
// 级联选择器的默认配置
const defaultCascaderProps = {
  value: "value",
  label: "label",
  children: "children",
  checkStrictly: false,
  multiple: false,
  emitPath: true,
};
// 获取基础表单验证规则
const getBaseRules = () => {
  const baseRules = {};
  props.formItems.forEach((rowItem) => {
    if (rowItem.list) {
      rowItem.list.forEach((item) => {
        if (item.prop && item.rules) {
          baseRules[item.prop] = item.rules;
        }
      });
    }
  });
  return baseRules;
};
// 表单验证规则
const rules = {
  ...getBaseRules(),
};

const initBaseFormData = () => {
  const baseData = {};
  props.formItems.forEach((rowItem) => {
    if (rowItem.list) {
      rowItem.list.forEach((item) => {
        if (item.prop) {
          // 根据表单项类型初始化不同的默认值
          if (item.type === "checkbox") {
            baseData[item.prop] = []; // checkbox类型初始化为空数组
          } else if (item.type === "switch") {
            baseData[item.prop] = 2; // switch类型初始化为2
          } else {
            baseData[item.prop] = ""; // 其他类型初始化为空字符串
          }
        }
      });
    }
  });
  return baseData;
};
// 表单数据
const formData = reactive({
  ...initBaseFormData(), // 基础表单数据
});

watch(
  () => props.formItems,
  (newFormItems) => {
    if (newFormItems && newFormItems.length > 0) {
      // 更新基础表单数据结构
      const baseData = initBaseFormData();
      Object.keys(baseData).forEach((key) => {
        if (!(key in formData)) {
          formData[key] = "";
        }
      });
    }
  },
  { immediate: true }
);
// 初始化方法

const inputOptions=ref([])
const selectedOption = ref(null);

// 监听dialogVisible变化
watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val;
  }
);

watch(
  () => dialogVisible.value,
  (val) => {
    emit("update:modelValue", val);
  }
);

const actualCurrentStep = computed(() => {
  return props.operationName !== "新增"
    ? props.currentStep + 1
    : props.currentStep;
});

// 关闭弹窗
const handleClose = () => {
  isFileName.value=true
  resetForm();
  dialogVisible.value = false;
  emit("close");
  emit("cancel");
};
// 提交表单
const handleSubmit = async () => {

  if (props.isView || !formRef.value) return;
  try {
    // 表单验证
    await formRef.value.validate();
    // 深拷贝数据，避免修改原始数据
    let submitData = JSON.parse(JSON.stringify({ ...formData }));
    // 处理多选数组字段，转换为字符串
    const arrayFields = ["dataSummary", "analyticalChart"];
    arrayFields.forEach((field) => {
      if (Array.isArray(submitData[field])) {
        submitData[field] = submitData[field].join(",");
      }
    });
    isFileName.value=true;
    emit("handleDialogSubmit",submitData)
  } catch (error) {
    ElMessage.error(error.message || "提交失败，请检查表单");
  }
};
// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
    currentAuditLevel.value = 1;
    // 创建一个全新的初始状态
    const freshData = {
      ...initBaseFormData(), // 基础表单数据
    };
    // 重置所有数据
    Object.keys(formData).forEach((key) => {
      delete formData[key];
    });
    Object.assign(formData, freshData);
  }
};
watch(
  () => props.initialData,
  (val) => {
    if (val) {
      const formattedData = { ...val };

      // 将字符串转换为数组
      if (typeof formattedData.analyticalChart === "string") {
        formattedData.analyticalChart = formattedData.analyticalChart
          .split(",")
          .filter(Boolean);
      }
      if (typeof formattedData.dataSummary === "string") {
        formattedData.dataSummary = formattedData.dataSummary
          .split(",")
          .filter(Boolean);
      }
      // 合并初始数据
      Object.assign(formData, {
        ...initBaseFormData(),
        ...formattedData,
      });
    }
  },
  { immediate: true }
);
//图片上传成功回调
const imageUrl = ref("");
const fileName = ref("");
const handleImageSuccess = (newImageUrl, prop) => {
  formData[prop] = newImageUrl;
  imageUrl.value = newImageUrl;
};
// 文件上传成功回调
const handleFileSuccess = (file,prop) => {
  isFileName.value=false
  formData[prop] = file;
  fileName.value = file;
};
//下载文件
const FileDownload = async (data) => {
  await getFile(data).then(res => {
    if (res.code === 1) {
      ElMessage.error("文件不存在")
    } else {
      let fileUrl = 'http://localhost:8082/static/img/real/' + data;
      let extName = fileUrl.substring(fileUrl.lastIndexOf("."));
      const link = document.createElement('a');
      link.download = data + extName;
      link.href = fileUrl
      link.target = "_blank";
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    }
  })
}
// 删除文件
const FileDelete =async (data,prop) => {
  await getFile(data).then(async res => {
    if (res.code === 1) {
      ElMessage.error(res.message)
      return;
    }else {
      await removeFile(data).then(res => {
        if (res.code===0){
          isFileName.value=false
          formData[prop] = "";
          ElMessage.success("文件删除成功")
        }else if(res.code===1){
          ElMessage.error("删除失败")
        }

      })
    }
  })
}
// PDF和word转换
const handleHtmlContent = (data) => {
  emit('handleHtmlContent',data)
}
const htmlUpdate = (value,porp) => {
  formData[porp] = value
}
const dialogSelect = (data,value) => {
  if (!data){
    emit("dialogSelect",value)
  }
}

// 对外暴露方法
defineExpose({
  dialogVisible,
  formRef,
  formData,
  resetForm,
  handleSubmit,
});
</script>

<style lang="scss" scoped>
// 查看模式标题
.view-title {
  width: 100%;
  padding: 15px 20px;
  background-color: #f8f9fc;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #1f2937;
  margin: 10px 0 20px;

  &::before {
    content: "";
    display: inline-block;
    width: 4px;
    height: 16px;
    background-color: #409eff;
    border-radius: 2px;
    margin-right: 8px;
    vertical-align: middle;
  }
}

// 查看模式下的卡片样式调整
.audit-card {
  &.is-view {
    pointer-events: none; // 禁用鼠标事件

    &:hover {
      transform: none; // 禁用悬浮效果
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    }

    :deep(.el-card__header) {
      background: #f8f9fc; // 更柔和的头部背景
    }
  }
}
// 弹窗样式
:deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: 80vh;

  .el-dialog__header {
    padding: 20px;
    margin: 0;
    border-bottom: 1px solid #dcdfe6;
    flex-shrink: 0;
  }

  .el-dialog__body {
    flex: 1;
    overflow-y: auto;
    padding: 0;
    margin: 0;
    height: 0;
  }

  .el-dialog__footer {
    padding: 20px;
    margin: 0;
    border-top: 1px solid #dcdfe6;
    flex-shrink: 0;
  }
}
// 内容包装器
.dialog-content-wrapper {
  padding: 20px;
  box-sizing: border-box;
  max-height: 70vh;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(144, 147, 153, 0.3);
    border-radius: 3px;

    &:hover {
      background: rgba(144, 147, 153, 0.5);
    }
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }
}
// 基础样式
.box-padding {
  padding: 0 40px 0 5px;
}

.title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

// 底部按钮
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding-top: 20px;
}

// 禁用状态表单样式
:deep(.el-form--disabled) {
  .el-input__wrapper,
  .el-textarea__wrapper,
  .el-select .el-input__wrapper,
  .el-date-editor.el-input__wrapper {
    background-color: #f5f7fa;
    box-shadow: none;
  }

  .el-input__inner,
  .el-textarea__inner {
    color: #606266;
    -webkit-text-fill-color: #606266;
  }

  .el-form-item__label {
    color: #606266;
  }
}

// 进度条部分
.progress-section {
  background-color: #f8f9fc;
  border-radius: 8px;
  padding: 6px 0 15px 0;
  margin-bottom: 24px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 0 12px 0;
}

.progress-title {
  font-size: 16px;
  font-weight: 500;
  color: #1f2937;
  position: relative;
  padding-left: 12px;

  &::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background-color: #409eff;
    border-radius: 2px;
  }
}

.progress-extra {
  font-size: 14px;
  color: #6b7280;
}

// 步骤条样式
:deep(.el-steps) {
  .el-step__head {
    .el-step__line {
      background-color: #e5e7eb;
    }
  }

  .el-step__title {
    font-size: 14px;
    font-weight: 500;

    &.is-success {
      color: #409eff;
    }
    &.is-process {
      color: #1f2937;
    }
    &.is-wait {
      color: #9ca3af;
    }
  }

  .el-step__description {
    font-size: 12px;

    &.is-success {
      color: #6b7280;
    }
    &.is-process {
      color: #6b7280;
    }
    &.is-wait {
      color: #9ca3af;
    }
  }

  .el-step__head.is-process {
    color: #409eff;
    border-color: #409eff;
  }

  .el-step__title.is-process {
    color: #409eff;
  }

  .el-step__description.is-process {
    color: #409eff;
  }
}

// 自定义图标
.custom-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #fff;
  border: 2px solid #e5e7eb;
}

// 审核级别选择
.audit-level-group {
  width: 100%;
  margin: 10px 0 20px;
  display: flex;
  justify-content: center;
  padding: 15px;
  background-color: #f8f9fc;
  border-radius: 8px;

  .el-radio-group {
    display: flex;
    gap: 40px;
  }
}

// 卡片容器
.cards-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: nowrap; // 防止换行
  gap: 0;
  width: 100%;
  padding: 20px 0;
  flex-shrink: 0;
  min-height: 400px;
  position: relative;
}

// 审核卡片
.audit-card {
  flex: 1;
  min-width: 280px;
  max-width: 370px;
  transition: all 0.3s;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin: 0 15px;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }

  :deep(.el-card__header) {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
    background: linear-gradient(to right, #f8f9fc, #f2f4f8);
    border-radius: 8px 8px 0 0;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #1f2937;

    &::before {
      content: "";
      display: inline-block;
      width: 4px;
      height: 16px;
      background-color: #409eff;
      border-radius: 2px;
      margin-right: 8px;
      vertical-align: middle;
    }
  }

  .card-content {
    padding: 20px;

    :deep(.el-form-item) {
      margin-bottom: 20px;

      .el-form-item__label {
        font-weight: 500;
        color: #606266;
      }

      .el-input__wrapper,
      .el-select .el-input__wrapper {
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 0 0 1px #c0c4cc inset;
        }

        &.is-focus {
          box-shadow: 0 0 0 1px #409eff inset;
        }
      }

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

// 删除按钮
:deep(.el-button--text) {
  color: #f56c6c;
  transition: all 0.3s;
  padding: 4px 8px;
  border-radius: 4px;

  &:hover {
    color: #fff;
    background-color: #f56c6c;
  }

  .el-icon {
    vertical-align: middle;
    margin-right: 4px;
  }
}

// 时间限制输入框
.time-limit-input {
  display: flex;
  align-items: center;
  gap: 10px;

  :deep(.el-input-number) {
    width: 100%;

    .el-input-number__decrease,
    .el-input-number__increase {
      border-color: #dcdfe6;
      background-color: #f5f7fa;

      &:hover {
        color: #409eff;
      }
    }
  }

  .unit-text {
    color: #606266;
    font-weight: 500;
  }
}

.full-width {
  width: 100%;
}

// 响应式布局
@media screen and (max-width: 1200px) {
  .cards-container {
    flex-wrap: wrap;
    gap: 20px;
  }

  .audit-card {
    flex: 0 0 100%;
    max-width: none;
  }

  .arrow-container {
    display: none;
  }

  .audit-level-group {
    .el-radio-group {
      flex-wrap: wrap;
      justify-content: center;
    }
  }
}

// 小屏幕适配
@media screen and (max-width: 768px) {
  .box-padding {
    padding: 0 20px;
  }

  .audit-level-group {
    padding: 10px;
  }

  .cards-container {
    padding: 10px 0;
  }

  .card-content {
    padding: 15px;
  }
}
</style>
